'''
Author: Mr.Sen
LastEditTime: 2021-02-22 19:26:45
Description: 仅加载页面
Website: https://grimoire.cn
Copyright (c) Mr.Sen All rights reserved.
'''
import datetime, time, html, re
from django.http.response import JsonResponse
from django.shortcuts import redirect, render
from django.http import Http404
from database.models import *
from django.contrib.auth.decorators import login_required

# 正则表达式 匹配网址
regex = 'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+'

def isDarkMode():
    hour = datetime.datetime.now().hour
    # print(hour)
    # return True
    if 7 <= hour < 22:
        return False
    else:
        return True


def autoRender(request, template, ret):
    user = users.objects.get(id=request.user.id)
    iconList = []
    if ret.get("isMainPage", False):
        icons = user.icons.split("\n")
        while "" in icons:
            icons.remove("")
        
        for i in icons:
            key, value = i.split("@")
            if bool(re.match(regex, value)):
                iconList.append({"url":value, "icon":key})
            else:
                iconList.append({"url":"#", "icon":key})
    avatar = user.avatar if bool(re.match(regex, user.avatar)) else "/static/img/boy.png"
    iconfont = user.iconfont if bool(re.match(regex, user.iconfont)) else ""
    default = {
        "nickName": user.nicName,
        "avatar": avatar,
        "darkMod":isDarkMode(),
        "iconList":iconList,
        "iconfont":user.iconfont,
        "iconListString":user.icons,
    }
    default.update(ret)
    return render(request, template, default)


@login_required(login_url='/login/')
def mainPage(request):
    # 加载首页
    data = meta.objects.filter(user__id=str(request.user.id))
    res = {
        "pageName":"首页",
        "docId":0,
        "editMetaId":data.first().id,
        # "editMetaName":data.first().name,
        "range":range(len(data)),
        "isMainPage":True,
        # "needUserInfo":True
    }
    return autoRender(request, "main3.html", res)


@login_required(login_url="/login/")
def loadArticle(request):
    # 获取加载文章
    '''
    url="/doc/?p="
    直接请求文章，返回的数据是html
    '''
    docId = html.escape(request.GET.get("p", "0"))
    if not docId.isdigit():
        raise Http404()
    content = contents.objects.filter(id=docId).first()

    if content is None:
        raise Http404()

    if content.authorId != request.user.id and content.isPublic == "private":
        raise Http404()
    # print(content.text)
    # metaOfContent = meta.objects.get(id=content.meta.id)
    metaOfContent = content.meta
    # print(metaOfContent)
    time_local = time.localtime(content.created)
    #转换成新的时间格式(2016-05-05 20:28:54)
    dt = time.strftime("%Y-%m-%d",time_local)
    ret = {
        "text": content.text,
        "title": content.title,
        "docId": docId,
        "pageName": content.title,
        "alertMsg": "编辑文章",
        # "needUserInfo":False,
        "lastEdit":dt,
        "metaId":metaOfContent.id,
        # "author":users.objects.get(id=metaOfContent.user.id).nicName,
        "author":metaOfContent.user.nicName,
        "metaName":metaOfContent.name,
    }
    return autoRender(request, "doc.html", ret)


@login_required(login_url="/login/")
def metaInfo(request):
    # 加载分类页面
    '''
    url = "docOfMeta/?meta="
    用于加载分类页面
    '''
    metaId = request.GET.get("meta", "0")
    if not metaId.isdigit():
        print(1)
        raise Http404()

    metaInfo = meta.objects.filter(id=int(metaId)).first()
    if metaInfo is None:
        print(2)
        raise Http404()

    if metaInfo.user_id != request.user.id:
        print(3)

        raise Http404()

    ret = {
        "pageName": metaInfo.name,
        "docId": 0,
        "range": range(metaInfo.count),
        "metaCount":metaInfo.count,
        "metaId": metaId,
        "alertMsg": "新建文章",
        "editMeta":metaId,
    }

    return autoRender(request, "docInfo.html", ret)


# 加载编辑界面
@ login_required(login_url="/login/")
def writePage(request):
    '''
    url = "/editor/?edit="
    这里是渲染编辑器的函数
    主要是返回用户所拥有的分类数据
    以及要排查用户是否拥有这个文档
    是否存在这个文档
    是否新增文档
    '''
    metaOfUser = meta.objects.filter(user__id=request.user.id)

    editId = request.GET.get("edit", "0")
    editMeta = request.GET.get("editMeta", "0")
    
    if not editId.isdigit():
        return redirect(f"/editor/?edit=0&editMeta={metaOfUser.first().id}")
        
    if not editMeta.isdigit():
        return redirect(f"/editor/?edit={editId}&editMeta={metaOfUser.first().id}")

    
    # metaList = []
    # for i in metaOfUser:
    #     metaList.append({"id": i.id, "name": i.name})

    targetMeta = meta.objects.filter(id=int(editMeta)).first()
    if targetMeta is None or targetMeta.user.id != request.user.id:
        return redirect(f"/editor/?edit=0&editMeta={metaOfUser.first().id}")

    

    if editId == "0":  # 新建文章
        ret = {
            "pageName": "编辑器",
            "edit": 0,
            "title": "",
            "metaId": targetMeta.id,
            "metaName":targetMeta.name,
            "isPublic":"private",
            "alertMsg": "新建文章",
        }
        return autoRender(request, "writedoc.html", ret)

    else:
        content = contents.objects.filter(id=editId).first()

        if content is None:  # 检查文章存在性
            return redirect("/editor/?edit=0")

        if content.authorId != request.user.id:  # 检查是否拥有文章
            return redirect("/editor/?edit=0")
        ret = {
            "pageName": "编辑器",
            "edit": editId,
            "title": content.title,
            "metaId": content.meta_id,
            "isPublic":content.isPublic,
            "metaName":content.meta.name,
            "alertMsg": "新建文章",
        }
        return autoRender(request, "writedoc.html", ret)


@login_required(login_url="/login/")
def userCenter(request):
    # user = users.objects.get(id=request.user.id)

    ret = {
        "pageName": "用户中心",
        "edit": 0,
        "alertMsg": "新建文章",

    }
    return autoRender(request, "userCenter.html", ret)



@login_required(login_url="/login/")
def metaCenter(request):
    metas = meta.objects.filter(user__id=request.user.id)
    metaList = []
    for index, i in enumerate(metas):
        metaList.append({
            "index":index,
            "name":i.name,
            "date":time.strftime("%Y-%m-%d",time.localtime(i.lastEdit)),
            "isPublic":i.isPublic,
            "id":i.id,
            "count":i.count
        })

    ret = {
        "pageName":"编辑分类",
        "edit":0,
        "alertMsg": "新建文章",
        "metaList":metaList
    }
    return autoRender(request, "Classification.html", ret)
